package com.whynot.frame.manythread;

import java.util.ArrayList;
import java.util.List;

/**
 * wait/notify模拟中间件通信
 * @author Administrator
 *
 */
public class WaitNotifyThread {
	private static List list = new ArrayList();
	
	private void addList(){
		list.add("cy");
	}
	
	private int getSize(){
		return list.size();
	}
	
	public static void main(String[] args) {
		final WaitNotifyThread thread = new WaitNotifyThread();
		final Object lock = new Object();
		//final CountDownLatch latch = new CountDownLatch(1);
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				try {
						synchronized (lock) {
							for (int i = 0; i < 10; i++) {
								thread.addList();
								System.out.println("t1添加元素");
								Thread.sleep(1000);
								if(thread.getSize() == 5){
									System.out.println("通知其他线程，准备释放锁了");
									lock.notify();
									//latch.countDown();
								}
							} 
						}
					}catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
		});
		
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				try {
					synchronized (lock) {
						if(thread.getSize() != 5){
							System.out.println("t2进入了");
							Thread.sleep(3000);
							lock.wait();
							//latch.await();
						} 
						System.out.println("收到线程通知，停止线程");
						throw new RuntimeException();
					}
				}catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		});
		
		t2.start();
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		t1.start();
	}
	
}
